<?php

namespace App\Admin\Controllers;

use App\Models\RentCloth;
use App\Models\LogisticsInfo;
use App\Models\RentClothDetail;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Table;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use App\Admin\Extensions\RentCloth\SendOrder;
use App\Admin\Extensions\RentCloth\ConfirmOrder;
use Illuminate\Support\Facades\DB;



class RentClothLineController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '线上借还';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new RentCloth);
        $grid->model()->where('type', 1)->orderBy('id','desc');

        $grid->column('id', __('Id'));
        $grid->user()->nickname(__('用户昵称'));
        $grid->shop()->shop_name('店铺');
        
        $grid->column('created_at', __('创建时间'))->expand(function () {
            $datas = $this->logistics->map(function ($data, $key) {
                $data->key = $key + 1;
                $data->send_time = date('Y-m-d H:i:s', $data->send_time);
                return $data->only(['key', 'com_no', 'logistics_no', 'send_time']);
            });        
            return new Table(['ID', '物流公司', '物流单号', '发货时间'], $datas->toArray());
        });
        $grid->column('status', __('状态'))->display(function ($value) {
            switch ($value) {
                case '3':
                    return "<span class='label label-danger'>待发货</span>";                  
                    break;
                case '4':
                    return "<span class='label label-warning'>已发货</span>";
                    break;
                case '5':
                    return "<span class='label label-success'>已收货</span>";
                    break;
                case '2':
                    return "<span class='label label-primary'>已归还</span>";
                    break;
                
                default:
                    return "<span class='label label-success'>无</span>";
                    break;
            }
        });
        $grid->column('is_apply','申请还衣')->display(function($value){
            switch ($value){
                case '0':
                    return "<span class='label label-warning'>否</span>";
                    break;
                case '1':
                    return "<span class='label label-success'>是</span>";
                    break;
            }
        });
        $grid->column('back_time', __('归还时间'))->display(function ($value) {
            if ($value) {
                return date('Y-m-d H:i:s', $value);
            }
        });
        
        $grid->filter(function ($filter) {
            $filter->disableIdFilter();
            $filter->scope('待发货')->where('status', 3);
            $filter->scope('已发货')->where('status', 4);
            $filter->scope('已收货')->where('status', 5);
            $filter->scope('已归还')->where('status', 2);
            $filter->scope('申请还衣')->where('is_apply', 1);

            $filter->between('created_at', '借衣时间')->datetime();
        });
        $grid->actions(function ($actions) {
            $actions->disableView();
            $actions->disableEdit();
            $actions->disableDelete();

            if($actions->row->status == 3){
                $actions->append(new SendOrder($actions->getKey()));
            }
            if($actions->row->status == 4){
                $actions->append(new ConfirmOrder($actions->getKey()));
            }
            if($actions->row->is_apply == 1){
                $actions->append("<a href='/admin/rentClothAddress?rent_id=" . $actions->getKey() . "'>" . "<button type='button' class='btn btn-primary'>地址</button></a>");
            }
            $actions->append("<a href='/admin/rentClothDetail?rent_id=" . $actions->getKey() . "'>" . '<i class="fa fa-sort-amount-asc"></i>' . "详情</a>");
        });

        $grid->disableCreateButton();
        return $grid;
    }

    //步骤详情
    public function rentClothDetail(Request $request)
    {   
        
        $details = RentClothDetail::where('rent_id',$request->rent_id)->with(['commodity','commodityAttr'])->get();
        
        $headers = ['ID','衣服名称', '图片', '属性'];
        $ret = [];
        foreach ($details as $v) {
            $step_img_arr = $v->commodity->pictures;
            
            $ret[] = [$v->id, $v->commodity->commodity_name,"<img src='/uploads/" . $step_img_arr[0] . " ' style='max-width:200px;max-height:200px' class='img img-thumbnail'>", $v->commodityAttr->attr_value];

        }
        $table = new Table($headers, $ret);

        $box = new Box('租衣详情', $table->render());
        $box->style('primary');
        $box->solid();
        $box->back();

        $content = new Content();
        return $content
            ->header('租衣详情')
            ->description('详情')
            ->body($box->render());
    }
    //地址详情
    public function rentClothAddress(Request $request)
    {   
        
        $details = LogisticsInfo::where([['rent_id',$request->rent_id],['type',1]])->with(['userAddr'])->first();
        
        $headers = ['ID','收件人', '电话', '地址','申请时间'];
        $ret = [];
        $addr = $details->userAddr;
        $apply_at = RentCloth::where('id',$request->rent_id)->value('updated_at');            
        $ret[] = [$addr->id, $addr->username,$addr->phone, $addr->all_address,$apply_at->toDateTimeString()];
        

        $table = new Table($headers, $ret);

        $box = new Box('收货地址', $table->render());
        $box->style('primary');
        $box->solid();
        $box->back();

        $content = new Content();
        return $content
            ->header('地址详情')
            ->description('详情')
            ->body($box->render());
    }

    protected function detail($id)
    {
        $show = new Show(RentCloth::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('user_id', __('User id'));
        $show->field('shop_id', __('Shop id'));
        $show->field('com_id', __('Com id'));
        $show->field('com_attr_id', __('Com attr id'));
        $show->field('rent_time', __('Rent time'));
        $show->field('back_time', __('Back time'));
        $show->field('status', __('Status'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

     /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new RentCloth);

        $form->number('user_id', __('User id'));
        $form->number('shop_id', __('Shop id'));
        $form->number('commodity_id', __('Com id'));
        $form->number('commodity_attr_id', __('Com attr id'));
        $form->number('rent_time', __('Rent time'));
        $form->number('back_time', __('Back time'));
        $form->switch('status', __('Status'));

        return $form;
    }

    public function sendOrder(Request $request)
    {
        $rent_id = $request->id;
        list($com_no,$logistics_no) = explode('/',$request->info);
        $rent_data = RentCloth::where('id',$rent_id)->first();
        $rent_data->status = 4;
        
        DB::beginTransaction();
        try {
            $rent_data->save();
            LogisticsInfo::create([
                'rent_id' => $rent_id,
                'type' => 1,
                'addr_id' => $rent_data->addr_id,
                'com_no' => $com_no,
                'logistics_no' => $logistics_no,
                'send_time' => time(),
            ]);
            DB::commit();
            admin_success('发货成功', '成功.');            
            
        } catch (\Exception $exception) {
            
            DB::rollBack();
            admin_error('发货失败', '失败.');
        }
    }
    public function confirmOrder(Request $request)
    {
        $rent_id = $request->id;
        $rent_data = RentCloth::where('id',$rent_id)->first();
        $logistic = LogisticsInfo::where(['rent_id'=>$rent_id,'type'=>1])->first();
        $rent_data->status = 5;
        $logistic->receive_time = time();
        DB::beginTransaction();
        try {
            $rent_data->save();
            $logistic->save();
            DB::commit();
            admin_success('收货成功', '成功.');            
            
        } catch (\Exception $exception) {
            
            DB::rollBack();
            admin_error('收货失败', '失败.');
        }
    }




}
